<template>
  <div class="app-container">
    <div class="filter-container">
      <div style="float: right;">
        <el-button v-waves class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="handleAddWindow(0)">
          {{ $t('admin_user.button.add') }}
        </el-button>
      </div>
    </div>
    <el-table size="mini" v-loading="listLoading" :data="list" highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="60">
        <template slot-scope="{row}">
          <span>{{ row.Id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="160px" align="center" :label="$t('admin_user.table.nickname')">
        <template slot-scope="{row}">
          <span>{{ row.Username }}</span>
        </template>
      </el-table-column>

      <el-table-column width="200px" align="center" :label="$t('admin_user.table.email')">
        <template slot-scope="{row}">
          <span>{{ row.Email }}</span>
        </template>
      </el-table-column>
      <el-table-column width="160px" :label="$t('admin_user.table.role')" align="center">
        <template slot-scope="{row}">
          <el-button type="success" size="mini">{{ row.Name }}</el-button>
        </template>
      </el-table-column>
      <el-table-column width="160px" :label="$t('admin_user.table.register_time')" align="center">
        <template slot-scope="{row}">
          <span v-if="row.RegisterTime">{{ parseTime(row.RegisterTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="160px" :label="$t('admin_user.table.last_login_ip')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.LastLoginIp }}</span>
        </template>
      </el-table-column>

      <el-table-column width="160px" :label="$t('admin_user.table.last_login_time')" align="center">
        <template slot-scope="{row}">
          <span v-if="row.LastLoginTime">{{ parseTime(row.LastLoginTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" :label="$t('admin_user.table.state')" width="120">
        <template slot-scope="{row}">
          <i class="el-icon-check" style="color: green" v-if="row.State"></i>
          <i class="el-icon-close" style="color: red" v-if="!row.State"></i>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('admin_user.table.operate')">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-s-tools"
            @click="handleSettingWindow(row)"
          >
            {{ $t('admin_user.button.setting') }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEditPermissionDialog(row.Id)"
          >
            {{ $t('admin_user.button.acl') }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleStatus(row.Id)"
          >
            <span v-if="row.State">{{ $t('button.disable') }}</span>
            <span v-if="!row.State">{{ $t('button.enable') }}</span>
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDel(row.Id)"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" style="margin-top: 1px;" :page.sync="searchData.page_index" :limit="searchData.page_size" :page-sizes="pageSizes" @pagination="getList" />

    <!-- 弹窗  -->
    <el-dialog :title="$t('admin_user.window.add_window_title')" :visible.sync="dialogAddFormVisible">
      <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" label-width="140px" style="width: 800px; margin-left:50px;">
        <el-form-item :label="$t('admin_user.window.add_field_role')" prop="role_id">
          <el-select v-model="addData.role_id" placeholder="请选择角色">
            <el-option
              v-for="item in roleOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('admin_user.window.add_field_nickname')" prop="username">
          <el-input v-model="addData.username" placeholder="用户昵称, 显示用, 长度 6 - 24 之间!" style="width: 300px;" />
        </el-form-item>
        <el-form-item :label="$t('admin_user.window.add_field_email')" prop="email">
          <el-input v-model="addData.email" placeholder="登陆邮箱, 后台登陆用!" style="width: 300px;" />
        </el-form-item>
        <el-form-item :label="$t('admin_user.window.add_field_login_password')" prop="password">
          <el-input type="password" placeholder="登陆密码, 长度 6 - 24 之间!" v-model="addData.password" style="width: 300px;" />
        </el-form-item>
        <el-form-item :label="$t('admin_user.window.add_field_sec_password')" prop="sec_password">
          <el-input type="password" placeholder="安全密码, 重要操作时用到, 长度 6 - 24 之间!" v-model="addData.sec_password" style="width: 300px;" />
        </el-form-item>
        <el-form-item :label="$t('admin_user.window.add_field_avatar')" prop="image_avatar">
          <el-upload
            class="avatar-uploader"
            :action="imageUploadUrl"
            :show-file-list="false"
            :headers="uploadHeader"
            :on-success="handleUploadAvatarImageSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageAvatarUrl" :src="imageAvatarUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('button.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleAddSubmit()">
          {{ $t('button.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗  -->
    <el-dialog title="编辑权限" :visible.sync="dialogEditPermissionVisible">
      <el-form ref="dataPermissionForm" :rules="rules"  label-position="left" label-width="90px" style="width: 760px; margin-left:50px;">
        <el-tree
          :data="currentPermissions"
          show-checkbox
          node-key="id"
          accordion
          ref="permissionTree"
          :default-checked-keys="defaultCheckedPermissions"
          :props=" { children: 'children', label: 'label'}">
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('admin_user.button.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleEditPermissionSubmit()">
          {{ $t('admin_user.button.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗  -->
    <el-dialog :title="$t('admin_user.window.setting_window_title')" :visible.sync="dialogSettingFormVisible">
      <el-tabs v-model="activeTabName" @tab-click="handleTabClick" style="margin-left: 20px">
        <el-tab-pane :label="$t('admin_user.window.setting_tab_login_password')" name="login_password">
          <el-form ref="loginPasswordForm" :rules="modifyLoginPasswordRules" :model="loginPasswordData" label-position="left" label-width="210px" style="width: 800px; margin-left:50px;">
            <el-form-item :label="$t('admin_user.window.setting_label_current_user')" prop="currentUsername">
              <span style="color: red;">{{ currentSettingUser.Email }}</span>
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_login_field_password')" prop="password">
              <el-input v-model="loginPasswordData.password" placeholder="长度6 - 24位" show-password style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_login_field_confirm')" prop="confirm_password">
              <el-input v-model="loginPasswordData.confirm_password" placeholder="长度6 - 24位" show-password style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_login_field_sec')" prop="current_sec_password">
              <el-input v-model="loginPasswordData.current_sec_password" placeholder="当前操作用户的安全密码" show-password style="width: 380px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSettingSubmit('login')">
                {{ $t('admin_user.button.confirm') }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="$t('admin_user.window.setting_tab_sec_password')" name="sec_password">
          <el-form ref="secPasswordForm" :rules="modifySecPasswordRules" :model="secPasswordData" label-position="left" label-width="210px" style="width: 800px; margin-left:50px;">
            <el-form-item :label="$t('admin_user.window.setting_label_current_user')" prop="currentUsername">
              <span style="color: red;">{{ currentSettingUser.Email }}</span>
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_sec_field_password')" prop="sec_password">
              <el-input v-model="secPasswordData.sec_password" placeholder="长度6 - 24位" type="password" style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_sec_field_confirm')" prop="confirm_sec_password">
              <el-input v-model="secPasswordData.confirm_sec_password" placeholder="长度6 - 24位" type="password" style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_sec_field_sec')" prop="current_sec_password">
              <el-input v-model="secPasswordData.current_sec_password" placeholder="当前操作用户的安全密码" type="password" style="width: 380px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSettingSubmit('sec')">
                {{ $t('admin_user.button.confirm') }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="$t('admin_user.window.setting_tab_sec_base_info')" name="base_info">
          <el-form ref="baseInfoForm" :rules="modifyBaseInfoRules" :model="baseInfoData" label-position="left" label-width="170px" style="width: 800px; margin-left:50px;">
            <el-form-item :label="$t('admin_user.window.setting_label_current_user')" prop="currentUsername">
              <span style="color: red;">{{ currentSettingUser.Email }}</span>
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_info_field_nickname')" prop="username">
              <el-input v-model="baseInfoData.username" placeholder="长度6 - 24位" style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('admin_user.window.setting_info_field_avatar')" prop="image_avatar">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="uploadHeader"
                :on-success="handleUploadAvatarImageSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageAvatarUrl" :src="imageAvatarUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSettingSubmit('info')">
                {{ $t('admin_user.button.confirm') }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  adminUserList,
  adminUserAdd,
  adminUserSetting,
  adminUserDel,
  adminUserState,
  adminUserGetPermission, adminUserEditPermission
} from '@/api/admin'
import waves from '@/directive/waves'
import { parseTime } from '@/utils/index'
import Pagination from '@/components/Pagination'
import { getToken } from '@/utils/auth'
import { strLength } from '@/utils/common'
import local from '@/lang/systems/admin_user'

export default {
  name: 'AdminUserList',
  directives: { waves },
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '禁用',
        '1': '启用'
      }
      return statusMap[status]
    }
  },
  data() {
    const checkUsername = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 用户名不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 24 || strLen < 6) {
        return callback(new Error('对不起， 用户名长度为6-24个字符,汉字为3个字符!'))
      }

      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 用户名只能包含汉字,数字,字母'))
      } else {
        callback()
      }
    }
    const checkPassword = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 密码不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 24 || strLen < 6) {
        return callback(new Error('对不起， 密码长度为6-24个字符!'))
      }

      const reg = /^[A-Za-z0-9_]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 密码只能包含数字,字母,下划线'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      pageSizes: [10, 15, 20, 25, 30, 50, 100],
      listLoading: true,
      currentAction: '添加管理员',
      total: 0,
      searchData: {
        page_index: 1,
        page_size: 15
      },
      currentSettingUser: {},
      loginPasswordData: {
        action: 'login',
        id: 0,
        password: '',
        confirm_password: '',
        current_sec_password: ''
      },
      secPasswordData: {
        action: 'sec',
        id: 0,
        sec_password: '',
        confirm_sec_password: '',
        current_sec_password: ''
      },
      baseInfoData: {
        action: 'info',
        id: 0,
        username: '',
        image_avatar: ''
      },
      currentPermissionUser: {},
      permissionData: {
        id: 0,
        permission_ids: []
      },
      addData: {
        id: 0,
        role_id: '',
        username: '',
        email: '',
        password: '',
        image_avatar: '',
        fund_password: ''
      },
      roleOption: [],
      dialogAddFormVisible: false,
      dialogSettingFormVisible: false,

      dialogEditPermissionVisible: false,
      currentEditPermissionId: 0,
      currentPermissions: [],
      defaultCheckedPermissions: [],

      rules: {
        role_id: [{ required: true, message: '需要选择角色', trigger: 'blur' }],
        username: [
          { required: true, message: '需要填写用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        email: [
          { type: 'email', required: true, message: '需要填写邮箱', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '需要填写登陆密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        sec_password: [
          { required: true, message: '需要填写安全密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        image_avatar: [
          { required: true, message: '需要填写确认头像', trigger: 'blur' },
          { min: 6, max: 126, message: '长度在 6 到 128 个字符之间', trigger: 'blur' }
        ]
      },
      modifyLoginPasswordRules: {
        id: [{ required: true, message: '需要指定管理员', trigger: 'submit' }],
        password: [
          { required: true, message: '需要填写登陆密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        confirm_password: [
          { required: true, message: '需要填写确认登陆密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        current_sec_password: [{ required: true, message: '需要填写当前登陆用户安全密码', trigger: 'blur' }]
      },
      modifySecPasswordRules: {
        id: [{ required: true, message: '需要指定管理员', trigger: 'submit' }],
        sec_password: [
          { required: true, message: '需要填写安全密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        confirm_sec_password: [
          { required: true, message: '需要填写确认安全密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        current_sec_password: [{ required: true, message: '需要填写当前登陆用户安全密码', trigger: 'blur' }]
      },
      modifyBaseInfoRules: {
        id: [{ required: true, message: '需要指定管理员', trigger: 'submit' }],
        username: [
          { required: true, message: '需要填写昵称', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        image_avatar: [
          { required: true, message: '需要填写确认头像', trigger: 'blur' },
          { min: 6, max: 126, message: '长度在 6 到 128 个字符之间', trigger: 'blur' }
        ]
      },
      activeTabName: 'login_password',
      imageAvatarUrl: '',
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'admin/user/uploadAvatar'
    }
  },
  created() {
    this.getList()
    if (!this.$i18n.getLocaleMessage('en')['admin_user']) {
      this.$i18n.mergeLocaleMessage('en', local.en)
      this.$i18n.mergeLocaleMessage('zh', local.zh)
      this.$i18n.mergeLocaleMessage('es', local.es)
      this.$i18n.mergeLocaleMessage('ja', local.ja)
    }
  },
  computed: {
    uploadHeader() {
      return { Authorization: 'bearer ' + getToken() }
    }
  },
  methods: {
    resetAddData() {
      this.imageAvatarUrl = ''
      this.addData = {
        id: 0,
        role_id: '',
        username: '',
        image_avatar: '',
        email: '',
        password: '',
        fund_password: ''
      }
    },
    async getList() {
      this.listLoading = true
      const { data } = await adminUserList(this.searchData)
      this.list = data.data
      this.total = data.total
      this.roleOption = data.role_option
      this.listLoading = false
    },
    handleFilter() {
      this.searchData.page_index = 1
      this.getList()
    },
    handleAddWindow() {
      this.resetAddData()
      this.dialogAddFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          adminUserAdd(this.addData).then((response) => {
            if (response.success) {
              this.dialogAddFormVisible = false
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleSettingWindow(item) {
      this.resetLoginPasswordData()
      this.resetSecPasswordData()
      this.resetBaseInfoData()
      this.loginPasswordData.id = item.Id
      this.secPasswordData.id = item.Id

      this.baseInfoData.id = item.Id
      this.baseInfoData.image_avatar = item.ImageAvatar
      this.imageAvatarUrl = item.ImageAvatarUrl
      this.baseInfoData.username = item.Username

      this.currentSettingUser = item
      this.dialogSettingFormVisible = true
      this.$nextTick(() => {
        this.$refs['loginPasswordForm'].clearValidate()
        this.$refs['secPasswordForm'].clearValidate()
      })
    },
    handleSettingSubmit(sign) {
      let type, data
      if (sign === 'login') {
        this.$refs['secPasswordForm'].clearValidate()
        this.$refs['baseInfoForm'].clearValidate()
        type = 'loginPasswordForm'
        data = this.loginPasswordData
      } else if (sign === 'sec') {
        this.$refs['loginPasswordForm'].clearValidate()
        this.$refs['baseInfoForm'].clearValidate()
        type = 'secPasswordForm'
        data = this.secPasswordData
      } else if (sign === 'info') {
        this.$refs['loginPasswordForm'].clearValidate()
        this.$refs['secPasswordForm'].clearValidate()
        type = 'baseInfoForm'
        data = this.baseInfoData
      } else {
        this.$message({
          type: 'error',
          message: '对不起, 无效的操作'
        })
        return true
      }

      this.$refs[type].validate((valid) => {
        if (valid) {
          adminUserSetting(data).then((response) => {
            if (response.success) {
              this.dialogSettingFormVisible = false
              this.$message({
                type: 'success',
                message: response.msg
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    resetLoginPasswordData() {
      this.currentSettingUser = {}
      this.loginPasswordData = {
        action: 'login',
        id: 0,
        password: '',
        confirm_password: '',
        current_sec_password: ''
      }
    },
    resetSecPasswordData() {
      this.currentSettingUser = {}
      this.secPasswordData = {
        action: 'sec',
        id: 0,
        sec_password: '',
        confirm_sec_password: '',
        current_sec_password: ''
      }
    },
    resetBaseInfoData() {
      this.currentSettingUser = {}
      this.baseInfoData = {
        action: 'info',
        id: 0,
        username: '',
        image_avatar: ''
      }
    },
    handleStatus(id) {
      this.$confirm('此操作将禁用/启用指定管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminUserState(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '设置成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除选择用户, 并删除角色/权限分配, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminUserDel(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleTabClick(tab, event) {
    },
    parseTime(time, format) {
      return parseTime(time, format)
    },
    handleEditPermissionDialog(id) {
      this.dialogEditPermissionVisible = true
      this.currentEditPermissionId = id
      adminUserGetPermission(id).then((response) => {
        if (response.success) {
          this.currentPermissions = response.data.current_permissions
          this.defaultCheckedPermissions = response.data.checked_permissions
        }
      })
    },
    handleEditPermissionSubmit() {
      const permissions = this.getCheckedPermissionsKeys()
      adminUserEditPermission(this.currentEditPermissionId, permissions).then((response) => {
        if (response.success) {
          this.dialogEditPermissionVisible = false
          this.$message({
            type: 'success',
            message: '编辑权限成功!'
          })
        } else {
          this.$message({
            type: 'success',
            message: response.msg
          })
        }
      })
    },
    getCheckedPermissionsKeys() {
      return this.$refs.permissionTree.getCheckedKeys()
    },
    beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }

      if (file.size / 1024 > 200) {
        this.$message.error('上传头像图片大小不能超过 200K!')
        return false
      }
      return true
    },
    handleUploadAvatarImageSuccess(res, file) {
      if (res.success) {
        this.baseInfoData.image_avatar = res.data.file_name
        this.addData.image_avatar = res.data.file_name
        this.imageAvatarUrl = URL.createObjectURL(file.raw)
      }
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>
